#include "func.h"
#include "config.h"
#include "log.h"

int read_conf(const char *path, config_t *configs, int *n) {
    FILE *fp = fopen(path, "r");
    if(!fp) {
        NETDISK_LOG_ERR("Failed to open conf");
        return -1;
    }

    char buf[1024] = {0};
    int i = 0;

    while(fgets(buf, sizeof(buf), fp) != NULL){
        if(buf[0] == '#' || buf[0] == '\n') {
            continue;
        }
        char *key = strtok(buf, " ");
        if(!key) {
            NETDISK_LOG_ERR("Invalid key");
            continue;
        }

        char *value = strtok(NULL, "\n");
        if(!value) {
            NETDISK_LOG_ERR("Invalid value");
            continue;
        }

        configs[i].key = strdup(key);
        configs[i].value = strdup(value); 
        ++i;
    }

    fclose(fp);
    *n = i;
    return 0;
}

int get_conf_value(const config_t *configs, const int n, const char *key, char *value) {
    for(int i = 0; i < n; ++i) {
        if(strcmp(configs[i].key, key) == 0) {
            strncpy(value, configs[i].value, strlen(configs[i].value));
            return 0;
        }
    }
    return -1;
}

int free_configs(config_t *configs, int n) {
    for (int i = 0; i < n; ++i) {
        free(configs[i].key);
        free(configs[i].value);
    }
    return 0;
}
